package com.zkq.graduate.service.impl;


import com.zkq.graduate.mapper.UserMapper;
import com.zkq.graduate.pojo.Permission;
import com.zkq.graduate.pojo.Role;
import com.zkq.graduate.pojo.Users;
import com.zkq.graduate.service.UserService;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.*;

import static java.util.stream.Collectors.toList;


/**
 * @Author zhangkaiqiang
 * @Date 2019/9/24  15:18
 * @Description TODO
 */
@Service("userService")
public class UserServiceImpl implements UserService {

	@Resource
	private UserMapper userMapper;

	@Resource
	private RedisTemplate redisTemplate;


	@Override
	public Optional<Users> findUserById(int id) {
		return Optional.ofNullable(null);
	}

	@Override
	public int updateUser(Users users) {
		return 0;
	}

	@Override
	public Optional<Users> findUserByAccount(Users users) {
		return Optional.ofNullable(userMapper.findUserByAccount(users.getAccount()));
	}

	@Override
	public Optional<Users> findUserByPhone(Users users) {
		return Optional.ofNullable(userMapper.findUserByPhone(users.getPhone()));
	}

	@Override
	public List<Permission> getUserSystemPermission(HttpServletRequest request) {

		List<Permission> allPermission=new ArrayList<>();
		List<Permission> parentPermission=new ArrayList<>();

		// 查找一个用户对应的所有角色
		List<Role> roleList= (List<Role>) request.getAttribute("role");

		// 查看用户-角色拥有的所有系统菜单权限
		roleList.forEach((item)->{
			List<Permission> permissionList=(List<Permission>) redisTemplate.opsForHash().get("roleAndPermission",item.getRoleName());
			allPermission.addAll(permissionList.stream().filter(items->{
				return Objects.equals("系统菜单", items.getRemark());
			}).collect(toList()));
		});

		// 得到所有的父级菜单
		parentPermission=allPermission.stream().filter((item)->{
			return Objects.equals("#", item.getUrl());
		}).collect(toList());


		// 循环得到父级菜单权限下的所有子菜单权限
		for(Permission parent:parentPermission){
			List<Permission> childPermission=new LinkedList<>();
			for(Permission child:allPermission){
				if(Objects.equals(child.getParentId(),parent.getId())){
					childPermission.add(child);
				}
			}
			parent.setChildPermission(childPermission);
		}
		return parentPermission;
	}

	@Override
	public boolean batchInsertUser(List<Map<String, String>> users) {
		if(CollectionUtils.isEmpty(users)){
			return false;
		}
		return userMapper.batchInsertUser(users)==users.size();
	}
}
